<?php

namespace App\Service\Cruise\Check;

use App\Jobs\Message\FsMessageJob;
use App\Library\Rms\RmsShopApi;
use App\Library\Rms\RmsUserApi;
use App\Models\Common\ConfigModel;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyRoleMappingModel;
use App\Models\Common\FsCompanyUserModel;
use App\Models\Cruise\CruiseCheckCompanyModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckSelfDetailModel;
use App\Models\Cruise\CruiseCheckTaskGroupModel;
use App\Models\Cruise\CruiseCheckTaskModel;
use App\Models\Cruise\CruiseOrderExamineLogModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseOrderProcessModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Service\BaseService;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\System\SystemNotifyService;
use Illuminate\Support\Facades\Log;

/**
 * 文档：https://onepiece-group.feishu.cn/wiki/wikcnUc0ENl5aSRNU3Xjxag7Dk7?sheet=K1fKVq
 */
class CruiseCheckFsService extends BaseService
{
    private ?CruiseCheckDetailModel $cruiseCheckDetailModel;
    private ?CruiseOrderModel       $cruiseOrderModel;
    private string                  $module;
    private int                     $orgId = 0;

    public function __construct(?CruiseCheckDetailModel $cruiseCheckDetailModel, ?CruiseOrderModel $cruiseOrderModel)
    {
        $this->cruiseCheckDetailModel = $cruiseCheckDetailModel;
        $this->cruiseOrderModel       = $cruiseOrderModel;

        if ($this->cruiseOrderModel) {
            if (!in_array($cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_5, CruiseTemplateModel::TYPE_8])) {
                self::throwErr("稽核飞书推送，需要配置新的templateType: {$cruiseOrderModel->type}");
            }
        }
    }

    /**
     * 待提交 - 批量
     */
    public function submitBatch(
        CruiseCheckTaskModel $cruiseCheckTaskModel,
        CruiseCheckTaskGroupModel $checkTaskGroupModel
    ) {
        // 内部人员 + 机构负责人
        $userIds = [];

        if ($checkTaskGroupModel->companyId) {

            // 机构负责人
            $userIds = ConfigModel::getCruiseCheckAudit($checkTaskGroupModel->companyId, $cruiseCheckTaskModel->templateType);

        } else {

            // 内部人员
            $userIds[] = $checkTaskGroupModel->userId;
        }

        list($users, $_) = $this->prepareUserShops($userIds);

        $shop        = (new RmsShopApi())->getShopByIds([$checkTaskGroupModel->shopIdsArr[0] ?? 0])['data']['shopList'][0] ?? [];

        $sendSmsUserIds = [];
        $taskName = $cruiseCheckTaskModel->name ?? '';
        foreach ($userIds as $userId) {
            $dealName = $users[$userId]['username'] ?? '';
            $createdAt = date('Y-m-d', $cruiseCheckTaskModel->startTime);
            $expiredAt = date('Y-m-d', $cruiseCheckTaskModel->endTime);

            if ($checkTaskGroupModel->companyId) {

                // 三方外部人员不发
                if ($cruiseCheckTaskModel->templateType == CruiseTemplateModel::TYPE_3) {
                    $sendSmsUserIds[] = $userId;
                    // $sendSmsMobile = collect($userAllInfo)->where('id', $userId)->first()['mobile'] ?? '';
                    // if (strlen($sendSmsMobile)) {
                    //     try {
                    //         CruiseCheckSmsService::sendInspectionTask($sendSmsMobile, 1, $taskName, '待提交');
                    //     } catch (\Exception $exception) {}
                    // }
                    continue;
                }

                $feishuId = FsCompanyUserModel::getFeishuId($userId, $checkTaskGroupModel->companyId);
                $orgId    = FsCompanyModel::getOrganizationIdByDepartmentId($checkTaskGroupModel->companyId);
                $this->setModule('cruiseCheckSupplier', $orgId);
            } else {
                $this->setModule('cruiseCheck');
                $feishuId = $users[$userId]['feishuUserId'] ?? '';
            }

            $url = $this->setUrl("pages/task-list/index");

            if ($cruiseCheckTaskModel->templateType == CruiseTemplateModel::TYPE_3) {

                $elementFields = [
                    $this->buildElementField("**【待处理通知】您有%s条任务待处理！**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**任务处理人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**门店信息：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务创建时间**\n%s"),
                    $this->buildElementField("**任务截止时间**\n%s"),
                ];

                $orderNum = count($checkTaskGroupModel->shopIdsArr);
                $shopName = ($shop['shopCode'] ?? '') . ( $shop['name'] ?? '');
                if ($orderNum > 1) {
                    $shopName .= "等" . $orderNum . "家门店";
                }

                $params = ["巡检报告待提交", $orderNum, $taskName, $dealName, $shopName, $createdAt, $expiredAt, $url];
            } elseif ($cruiseCheckTaskModel->templateType == CruiseTemplateModel::TYPE_5) {

                $elementFields = [
                    $this->buildElementField("**【待处理通知】您有%s条任务待处理！**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**任务处理人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**供应商名称：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务创建时间**\n%s"),
                    $this->buildElementField("**任务截止时间**\n%s"),
                ];

                // 供应商名称
                $firstCruiseCheckCompanyId = $checkTaskGroupModel->beCruiseCheckCompanyIdsArr[0] ?? 0;
                $companyName = CruiseCheckCompanyModel::getDataById($firstCruiseCheckCompanyId)['fsCompany']['name'] ?? '';
                $companyNum = count($checkTaskGroupModel->beCruiseCheckCompanyIdsArr);
                if ($companyNum > 1) {
                    $companyName .= "等" . $companyNum . "家供应商";
                }

                $params = ["巡检报告待提交", $companyNum, $taskName, $dealName, $companyName, $createdAt, $expiredAt, $url];

            } else {
                continue;
            }

            $this->sendV2('CruiseCheck/feishu/notifyTemplate/generalV2.json', $elementFields, $params, $feishuId);
        }

        return $sendSmsUserIds;
    }

    /**
     * 待审核
     * @return void
     */
    public function audit(): void
    {
        // 通知对应审核人员
        if ($this->cruiseOrderModel->status == CruiseOrderModel::STATUS_WAIT_MODIFY_EXT) {
            $userIds = ConfigModel::getCruiseCheckAudit($this->cruiseCheckDetailModel->companyId, $this->cruiseOrderModel->type);
        } else {
            if ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_5) {
                $userIds = object_get($this->cruiseOrderModel->cruiseCheckCompanyRel, 'kfManagerId', 0) ? [object_get($this->cruiseOrderModel->cruiseCheckCompanyRel, 'kfManagerId', 0)] : [];
            } else {
                $userIds = ConfigModel::getCruiseCheckAudit($this->cruiseCheckDetailModel->companyId, $this->cruiseOrderModel->type, FsCompanyRoleMappingModel::ROLE_ID_KF_REVIEWER);
            }
        }

        if (!$userIds) {
            BaseService::throwErr("companyId:{$this->cruiseCheckDetailModel->companyName} 未配置稽核审核人员");
        }

        list($users, $shop) = $this->prepareUserShops($userIds);

        foreach ($userIds as $userId) {
            $taskName = $this->cruiseOrderModel->getTaskName();
            $shopCode  = $shop['shopCode'] ?? '';
            $shopName  = $shop['name'] ?? '';
            $dealName  = $users[$userId]['username'] ?? '';
            $createdAt = date('Y-m-d', $this->cruiseCheckDetailModel->cruiseTaskRel->startTime);
            $expiredAt = date('Y-m-d', $this->cruiseCheckDetailModel->cruiseTaskRel->endTime);

            if ($this->cruiseOrderModel->status == CruiseOrderModel::STATUS_WAIT_MODIFY_EXT) {

                // 门店稽核 - 外部不发  定时脚本触发
                if ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_3) {
                    continue;
                }

                $feishuId = FsCompanyUserModel::getFeishuId($userId, $this->cruiseCheckDetailModel->companyId);
                $orgId    = FsCompanyModel::getOrganizationIdByDepartmentId($this->cruiseCheckDetailModel->companyId);

                $this->setModule('cruiseCheckSupplier', $orgId);
                $path = "pages/task-detail/task-detail?taskId={$this->cruiseOrderModel->id}&templateType={$this->cruiseOrderModel->type}";
                $url = $this->setUrl($path);
            } else {
                $feishuId = $users[$userId]['feishuUserId'] ?? '';
                $this->setModule('cruiseCheck');

                if ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_3) {
                    $pat = 'inspection/processing/audit';
                } elseif ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_5) {
                    $pat = 'inspection/factory/processing/audit';
                } elseif ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_8) {
                    $pat = 'inspection/self/processing/audit';
                } else {
                    $pat = 'inspection/processing/audit';
                }

                $path = "{$pat}&checkId={$this->cruiseOrderModel->id}&id={$this->cruiseCheckDetailModel->id}";

                $url = \App\Service\OpenShop\Feishu\BaseService::pcUrl($path);
            }

            if (in_array($this->cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_8])) {

                $elementFields = [
                    $this->buildElementField("**【待处理通知】您有一条待处理任务！**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**门店编号：**\n%s"),
                    $this->buildElementField("**门店名称：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务创建时间**\n%s"),
                    $this->buildElementField("**任务截止时间**\n%s"),
                ];

                $params = ["巡检报告待审核", $taskName, $dealName, $shopCode, $shopName, $createdAt, $expiredAt, $url];
            } elseif ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_5) {

                $elementFields = [
                    $this->buildElementField("**【待处理通知】您有一条待处理任务！**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**供应商名称：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务创建时间**\n%s"),
                    $this->buildElementField("**任务截止时间**\n%s"),
                ];

                // 供应商名称
                $companyName = CruiseCheckCompanyModel::getDataById($this->cruiseOrderModel->cruiseCheckCompanyId)['fsCompany']['name'] ?? '';

                $params = ["巡检报告待审核", $taskName, $dealName, $companyName, $createdAt, $expiredAt, $url];

            } else {
                continue;
            }

            if (config('app.env') != 'prod') {
                $elementFields[] = $this->buildElementField("**debug path：**\n {$path}");
                $elementFields[] = $this->buildElementField("**debug module：**\n {$this->module}");
            }

            $this->sendV2('CruiseCheck/feishu/notifyTemplate/generalV2.json', $elementFields, $params, $feishuId);
        }
    }

    /**
     * 完成
     * @return void
     */
    public function finish(int $currentUid): void
    {
        // 通知对应相关所有人员
        $totalUsers = $this->totalUsers(true);

        $userIds    = array_column($totalUsers, 'userId');

        $dealName = RmsUserService::getRmsUserInfoByUserIds([$currentUid])['data'][0]['username'] ?? '';

        list($_, $shop) = $this->prepareUserShops([]);

        foreach ($userIds as $userId) {
            $taskName = $this->cruiseOrderModel->getTaskName();
            $shopCode = $shop['shopCode'] ?? '';
            $shopName = $shop['name'] ?? '';
            $feishuId = $totalUsers[$userId]['feishuId'] ?? '';

            if ($totalUsers[$userId]['role'] == self::ROLE_KF) {
                $this->setModule('cruiseCheck', 0);
                $path = 'pages/task-detail/task-detail';
            } elseif ($totalUsers[$userId]['role'] == self::ROLE_EXT) {

                // 门店稽核 - 三方不发
                if ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_3) {
                    continue;
                }

                $this->setModule('cruiseCheckSupplier', $totalUsers[$userId]['orgId'] ?? 1);
                $path = 'pages/task-detail/task-detail';
            } elseif ($totalUsers[$userId]['role'] == self::ROLE_FACTORY) {
                $this->setModule('cruiseCheckFactory', $totalUsers[$userId]['orgId'] ?? 1);
                $path = 'pages/factory/task-detail/task-detail';
            } else {
                $this->setModule('cruiseCheck', 0);
                $path = 'pages/task-detail/task-detail';
            }
            $url = $this->setUrl("{$path}?taskId={$this->cruiseOrderModel->id}&templateType={$this->cruiseOrderModel->type}");

            if ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_3) {

                $elementFields = [
                    $this->buildElementField("**任务完成通知**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**门店编号：**\n%s"),
                    $this->buildElementField("**门店名称：**\n%s"),
                ];

                $params = ["巡检报告已完成", $taskName, $dealName, $shopCode, $shopName, $url];
            } elseif ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_5) {

                $elementFields = [
                    $this->buildElementField("**任务完成通知**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**供应商名称：**\n%s"),
                    $this->buildElementField(""),
                ];

                // 供应商名称
                $companyName = CruiseCheckCompanyModel::getDataById($this->cruiseOrderModel->cruiseCheckCompanyId)['fsCompany']['name'] ?? '';

                $params = ["巡检报告已完成", $taskName, $dealName, $companyName, $url];

            } else {
                continue;
            }

            $this->sendV2('CruiseCheck/feishu/notifyTemplate/generalV2.json', $elementFields, $params, $feishuId);
        }
    }

    /**
     * 巡检报告单个作废
     */
    public function offlineSingle(int $currentUid): void
    {
        // 通知对应相关所有人员
        $totalUsers = $this->totalUsers(false);
        $userIds    = array_column($totalUsers, 'userId');

        $dealName = RmsUserService::getRmsUserInfoByUserIds([$currentUid])['data'][0]['username'] ?? '';

        list($_, $shop) = $this->prepareUserShops($userIds);

        foreach ($userIds as $userId) {
            $taskName = $this->cruiseOrderModel->getTaskName();
            $shopCode = $shop['shopCode'] ?? '';
            $shopName = $shop['name'] ?? '';
            $feishuId = $totalUsers[$userId]['feishuId'] ?? '';

            if ($totalUsers[$userId]['role'] == self::ROLE_KF) {
                $this->setModule('cruiseCheck');
                $path = 'pages/task-detail/task-detail';
            } elseif ($totalUsers[$userId]['role'] == self::ROLE_EXT) {

                // 门店稽核 - 三方不发
                if ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_3) {
                    continue;
                }

                $this->setModule('cruiseCheckSupplier', $totalUsers[$userId]['orgId'] ?? 1);
                $path = 'pages/task-detail/task-detail';
            } elseif ($totalUsers[$userId]['role'] == self::ROLE_FACTORY) {
                $this->setModule('cruiseCheckFactory', $totalUsers[$userId]['orgId'] ?? 1);
                $path = 'pages/factory/task-detail/task-detail';
            } else {
                $this->setModule('cruiseCheck');
                $path = 'pages/task-detail/task-detail';
            }
            $url = $this->setUrl("{$path}?taskId={$this->cruiseOrderModel->id}&templateType={$this->cruiseOrderModel->type}");

            if ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_3) {

                $elementFields = [
                    $this->buildElementField("**任务作废通知**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**门店编号：**\n%s"),
                    $this->buildElementField("**门店名称：**\n%s"),
                ];

                $params = ["巡检报告已作废", $taskName, $dealName, $shopCode, $shopName, $url];
            } elseif ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_5) {

                $elementFields = [
                    $this->buildElementField("**任务作废通知**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**供应商名称：**\n%s"),
                    $this->buildElementField(""),
                ];

                // 供应商名称
                $companyName = CruiseCheckCompanyModel::getDataById($this->cruiseOrderModel->cruiseCheckCompanyId)['fsCompany']['name'] ?? '';

                $params = ["巡检报告已作废", $taskName, $dealName, $companyName, $url];

            } else {
                continue;
            }

            $this->sendV2('CruiseCheck/feishu/notifyTemplate/generalV2.json', $elementFields, $params, $feishuId);
        }
    }

    /**
     * 巡检报告被驳回
     * @return void
     */
    public function reject(int $currentUid, string $rejectContent): void
    {
        $users = [];

        // 提交人
        $submitUid = CruiseOrderProcessModel::query()
                                            ->where('cruiseOrderId', $this->cruiseCheckDetailModel->orderId)
                                            ->where('step', CruiseOrderProcessModel::PROCESS_SUBMITTED)
                                            ->first()['createdByUid'] ?? 0;

        // 三方审核人
        $threePartyAuditUserId = 0;

        // 门店自检 - 不给加盟商发了
//        if ($this->cruiseCheckDetailModel->templateType == CruiseTemplateModel::TYPE_8) {
//
//            // 给提交人推送商家app推送
//            $selfTaskId = (int)CruiseCheckSelfDetailModel::query()->where('cruiseOrderId', $this->cruiseOrderModel->id)->value('taskId');
//            $notify = SystemNotifyService::save(
//                false,
//                "任务驳回通知",
//                SystemNotifyCenterModel::NOTIFY_TYPE_3,
//                SystemNotifyCenterModel::NOTIFY_TARGET_1,
//                '',
//                "巡检报告已驳回，审核意见：{$rejectContent}",
//                config('webUrl.notify_web_cdn_url') . "#pages/shop-check/daily/main?id={$selfTaskId}",
//                SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
//                "巡检报告已驳回，审核意见：{$rejectContent}",
//                '',
//                SystemNotifyCenterModel::IS_POPUP_ON,
//                1,
//                $this->cruiseOrderModel->shopId
//            );
//            SystemNotifyService::recordLog($notify, '创建消息');
//            SystemNotifyService::preSend($notify->id, [$submitUid]);
//            return;
//        }

        if ($this->cruiseCheckDetailModel->companyId) {

            // 提交人
            list($role, $orgId) = $this->submiterRole();
            $users[] = [
                'userId' => $submitUid,
                'role'   => $role,
                'orgId'  => $orgId,
            ];

            // 三方审核人
            $threePartyAuditUserId = CruiseOrderProcessModel::query()
                ->where('cruiseOrderId', $this->cruiseCheckDetailModel->orderId)
                ->where('step', CruiseOrderProcessModel::PROCESS_EXT_REVIEWED)
                ->first()['createdByUid'] ?? 0;

            $users[] = [
                'userId' => $threePartyAuditUserId,
                'role'   => self::ROLE_EXT,
                'orgId'  => FsCompanyModel::getOrganizationIdByDepartmentId($this->cruiseCheckDetailModel->companyId),
            ];

        } else {

            // 提交人
            list($role, $orgId) = $this->submiterRole();
            $users[] = [
                'userId' => $submitUid,
                'role'   => $role,
                'orgId'  => $orgId,
            ];
        }

        $userIds   = array_column($users, 'userId');
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'])->keyBy('id');

        foreach ($users as &$v) {
            if (isset($v['feishuId']) && $v['feishuId']) {
                continue;
            }

            if ($v['role'] == self::ROLE_KF) {
                $v['feishuId'] = $userInfos[$v['userId']]['feishuUserId'] ?? '';
            } else {
//                $v['feishuId'] = FsCompanyUserModel::getFeishuId($v['userId'], $this->cruiseCheckDetailModel->companyId);
                $v['feishuId'] = (string)FsCompanyUserModel::query()->where('rmsUserId', $v['userId'])->where('ext', 1)->orderByDesc('id')->value('feishuId');
            }
        }

        $totalUsers = array_column($users, null, 'userId');

        // 通知对应相关所有人员
        $userIds    = array_column($totalUsers, 'userId');

        $userInfo    = (new RmsUserApi())->getUserInfoByIds([$currentUid, $submitUid, $threePartyAuditUserId], ['id', 'username', 'mobile'])['data'] ?? [];
        $dealName    = collect($userInfo)->where('id', $currentUid)->first()['username'] ?? '';
        $sendSms     = false;

        list($_, $shop) = $this->prepareUserShops($userIds);

        $taskName = $this->cruiseOrderModel->getTaskName();
        $shopCode = $shop['shopCode'] ?? '';
        $shopName = $shop['name'] ?? '';

        foreach ($userIds as $userId) {
            $feishuId = $totalUsers[$userId]['feishuId'] ?? '';

            if ($totalUsers[$userId]['role'] == self::ROLE_KF) {
                $this->setModule('cruiseCheck');
                $path = 'pages/task-detail/task-detail';
            } elseif ($totalUsers[$userId]['role'] == self::ROLE_EXT) {

                // 门店稽核 - 三方不发  给提交人发送消息
                if ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_3) {
                    $sendSms = true;
                    continue;
                }

                $this->setModule('cruiseCheckSupplier', $totalUsers[$userId]['orgId'] ?? 1);
                $path = 'pages/task-detail/task-detail';
            } elseif ($totalUsers[$userId]['role'] == self::ROLE_FACTORY) {
                $this->setModule('cruiseCheckFactory', $totalUsers[$userId]['orgId'] ?? 1);
                $path = 'pages/factory/task-detail/task-detail';
            } else {
                $this->setModule('cruiseCheck');
                $path = 'pages/task-detail/task-detail';
            }
            $url = $this->setUrl("{$path}?taskId={$this->cruiseOrderModel->id}&templateType={$this->cruiseOrderModel->type}");

//            $processId = CruiseOrderProcessModel::query()
//                                                ->where('cruiseOrderId', $this->cruiseCheckDetailModel->orderId)
//                                                ->where('step', CruiseOrderProcessModel::PROCESS_REVIEWED)
//                                                ->orderByDesc('id')
//                                                ->value('id');
//            $rejectContent = CruiseOrderExamineLogModel::query()->where('processId', $processId)->value('content') ?? '';


            if (in_array($this->cruiseOrderModel->type, [CruiseTemplateModel::TYPE_3, CruiseTemplateModel::TYPE_8])) {

                $elementFields = [
                    $this->buildElementField("**任务驳回通知**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**门店编号：**\n%s"),
                    $this->buildElementField("**门店名称：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务驳回通知：**\n%s"),
                ];

                $params = ["巡检报告已驳回", $taskName, $dealName, $shopCode, $shopName, $rejectContent, $url];
            } elseif ($this->cruiseOrderModel->type == CruiseTemplateModel::TYPE_5) {

                $elementFields = [
                    $this->buildElementField("**任务驳回通知**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**供应商名称：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务驳回通知：**\n%s"),
                ];

                // 供应商名称
                $companyName = CruiseCheckCompanyModel::getDataById($this->cruiseOrderModel->cruiseCheckCompanyId)['fsCompany']['name'] ?? '';

                $params = ["巡检报告已驳回", $taskName, $dealName, $companyName, $rejectContent, $url];

            } else {
                continue;
            }

            $this->sendV2('CruiseCheck/feishu/notifyTemplate/generalV2.json', $elementFields, $params, $feishuId);
        }

        if ($sendSms) {
            try {
                // 通知处理人
                $sendSmsSubmitMobile = collect($userInfo)->where('id', $submitUid)->first()['mobile'] ?? '';
                if (strlen($sendSmsSubmitMobile)) {
                    CruiseCheckSmsService::sendInspectionTask($sendSmsSubmitMobile, 1, $taskName, '已驳回，请立即处理');
                }

                // 通知三方审核人
                if ($threePartyAuditUserId > 0 && $threePartyAuditUserId != $currentUid) {
                    $sendSmsAuditMobile = collect($userInfo)->where('id', $threePartyAuditUserId)->first()['mobile'] ?? '';
                    if (strlen($sendSmsAuditMobile)) {
                        CruiseCheckSmsService::sendInspectionTask($sendSmsAuditMobile, 1, $taskName, '已驳回');
                    }
                }
            } catch (\Exception $exception) {}
        }
    }

    /**
     * 巡检任务作废 - 挨个报告作废推送
     * @param int $currentUid
     * @return void
     */
    public function offlineTask(int $currentUid, CruiseCheckTaskModel $cruiseCheckTaskModel): void
    {
        $lists = CruiseCheckDetailModel::query()
                                       ->join('cruise_order', 'cruise_order.id', '=', 'cruise_check_details.orderId')
                                       ->where('cruise_check_details.taskId', $cruiseCheckTaskModel->id)
                                       ->where('cruise_order.status', CruiseOrderModel::STATUS_CLOSED)
                                       ->select([
                                           'cruise_order.shopId',
                                           'cruise_order.cruiseCheckCompanyId',
                                           'cruise_check_details.dealUid',
                                           'cruise_check_details.companyId'
                                       ])
                                       ->get();

        $dealName = RmsUserService::getRmsUserInfoByUserIds([$currentUid])['data'][0]['username'] ?? '';
        $userIds = $lists->pluck('dealUid')->unique()->values()->toArray();

        list($users, $_) = $this->prepareUserShops($userIds);

        $shopIds = $lists->pluck('shopId')->toArray();
        $shops   = collect((new RmsShopApi())->getShopByIds($shopIds)['data']['shopList'] ?? [])->keyBy('id');

        foreach ($userIds as $userId) {

            // 所有的shopIds
            $shopIds  = $lists->where('dealUid', $userId)->pluck('shopId')->toArray();
            $shopId   = $shopIds[0] ?? 0;

            $taskName = $cruiseCheckTaskModel->name ?? '';

            $companyId = $lists->where('dealUid', $userId)->first()['companyId'];

            if ($companyId) {

                // 门店稽核 - 三方不发
                if ($cruiseCheckTaskModel->templateType == CruiseTemplateModel::TYPE_3) {
                    continue;
                }

                $feishuId = FsCompanyUserModel::getFeishuId($userId, $companyId);
                $orgId    = FsCompanyModel::getOrganizationIdByDepartmentId($companyId);
                $this->setModule('cruiseCheckSupplier', $orgId);
            } else {
                $feishuId = $users[$userId]['feishuUserId'] ?? '';
                $this->setModule('cruiseCheck');
            }

            $url = $this->setUrl("pages/task-list/index");

            if ($cruiseCheckTaskModel->templateType == CruiseTemplateModel::TYPE_3) {

                $elementFields = [
                    $this->buildElementField("**任务作废通知**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**门店编号：**\n%s"),
                    $this->buildElementField("**门店名称：**\n%s"),
                ];

                $shopCode = $shops[$shopId]['shopCode'] ?? '';
                $shopName = $shops[$shopId]['name'] ?? '';

                $shopName = "{$shopCode}{$shopName}";
                if (count($shopIds) > 1) {
                    $shopName .= "等" . count($shopIds) . "家门店";
                }

                $params = ["巡检报告已作废", $taskName, $dealName, $shopCode, $shopName, $url];
            } elseif ($cruiseCheckTaskModel->templateType == CruiseTemplateModel::TYPE_5) {

                $elementFields = [
                    $this->buildElementField("**任务作废通知**"),
                    $this->buildElementField(""),
                    $this->buildElementField("**任务名称：**\n%s"),
                    $this->buildElementField("**操作人：**\n%s"),
                    $this->buildElementField(""),
                    $this->buildElementField(""),
                    $this->buildElementField("**供应商名称：**\n%s"),
                    $this->buildElementField(""),
                ];

                // 供应商名称
                $firstCruiseCheckCompanyId = $lists->first()['cruiseCheckCompanyId'] ?? 0;
                $companyName = CruiseCheckCompanyModel::getDataById($firstCruiseCheckCompanyId)['fsCompany']['name'] ?? '';
                $companyNum = $lists->pluck('cruiseCheckCompanyId')->count();
                if ($companyNum > 1) {
                    $companyName .= "等" . $companyNum . "家供应商";
                }

                $params = ["巡检报告已作废", $taskName, $dealName, $companyName, $url];

            } else {
                continue;
            }

            $this->sendV2('CruiseCheck/feishu/notifyTemplate/generalV2.json', $elementFields, $params, $feishuId);
        }
    }

//    /**
//     * 执行发送 - 异步
//     * @param string $path
//     * @param array $params
//     * @param string $feishuId
//     * @return array
//     */
//    private function send(string $path, array $params, string $feishuId): void
//    {
//        $templateJson = vsprintf(file_get_contents(resource_path($path)), $params);
//
//        dispatch((new FsMessageJob($feishuId, json_decode($templateJson, true), $this->module)));
//    }

    /**
     * 准备user/shops数据
     * @param array $userIds
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function prepareUserShops(array $userIds): array
    {
        if ($userIds) {
            $users = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'])->keyBy('id');
        } else {
            $users = [];
        }

        if ($this->cruiseOrderModel) {
            $shop = (new RmsShopApi())->getShopByIds([$this->cruiseOrderModel->shopId])['data']['shopList'][0] ?? '';
        } else {
            $shop = [];
        }

        return [$users, $shop];
    }

    private function setModule(string $module, int $orgId = 0)
    {
        $this->module = $module;
        $this->orgId  = $orgId;
    }

    private function setUrl(string $path): string
    {
        $appid = ConfigModel::getFsConfigByPlatformNameOrgId($this->module, $this->orgId)['appId'] ?? '';

        $path  = urlencode($path);

        $url = "https://applink.feishu.cn/client/mini_program/open?appId={$appid}&mode=window-semi&relaunch=true&path={$path}";

        Log::info("CruiseCheckFsService setUrl url:{$url}");

        return $url;
    }

    const ROLE_KF  = 1; // 内部人
    const ROLE_EXT = 2; // 三方人
    const ROLE_FACTORY = 3; // 工厂人

    /**
     * @param bool $companyManager 是否通知工厂负责人
     * @return array
     */
    private function totalUsers(bool $companyManager = true): array
    {
        $users = [];

        $process = CruiseOrderProcessModel::query()
                                          ->where('cruiseOrderId', $this->cruiseCheckDetailModel->orderId)->get();

        // 提交人
        list($role, $orgId) = $this->submiterRole();
        $users[] = [
            'userId' => $process->where('step', CruiseOrderProcessModel::PROCESS_SUBMITTED)
                                ->first()['createdByUid'] ?? 0,
            'role'   => $role,
            'orgId'  => $orgId,
        ];

        // 三方审核人
        $userId = $process->where('step', CruiseOrderProcessModel::PROCESS_EXT_REVIEWED)->first()['createdByUid'] ?? 0;
        if ($userId) {
            $users[] = [
                'userId' => $userId,
                'role'   => self::ROLE_EXT,
                'orgId' =>  FsCompanyModel::getOrganizationIdByDepartmentId($this->cruiseCheckDetailModel->companyId),
            ];
        }

        // 总部审核人
        $userId = $process->where('step', CruiseOrderProcessModel::PROCESS_COMPLETED)->first()['createdByUid'] ?? 0;
        if ($userId) {
            $users[] = [
                'userId' => $userId,
                'role'   => self::ROLE_KF,
                'orgId'  => 0,
            ];
        }

        // 工厂联系人
        if ($companyManager && $this->cruiseOrderModel && $this->cruiseOrderModel->cruiseCheckCompanyId) {
            $users[] = [
                'userId' => CruiseCheckCompanyModel::getDataById($this->cruiseOrderModel->cruiseCheckCompanyId)['companyManager']['rmsUserId'] ?? 0,
                'role'   => self::ROLE_FACTORY,
                'orgId'  => CruiseCheckCompanyModel::getOrgIdById($this->cruiseOrderModel->cruiseCheckCompanyId),
            ];
        }

        $userIds   = array_column($users, 'userId');

        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'])->keyBy('id');

        foreach ($users as &$v) {
            if ($v['role'] == self::ROLE_KF) {
                $v['feishuId'] = $userInfos[$v['userId']]['feishuUserId'] ?? '';
            } else {
                $v['feishuId'] = (string)FsCompanyUserModel::query()->where('rmsUserId', $v['userId'])->where('ext', 1)->orderByDesc('id')->value('feishuId');
            }
        }

        return array_column($users, null, 'userId');
    }

    /**
     * 提交人的role
     * @return int
     */
    private function submiterRole(): array
    {
        if ($this->cruiseCheckDetailModel->checkType == CruiseCheckDetailModel::CHECK_TYPE_INSIDE) {

            // 内部
            $role = self::ROLE_KF;
            $orgId = 0;
        } elseif ($this->cruiseCheckDetailModel->checkType == CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY) {

            // 三方
            $role = self::ROLE_EXT;
            $orgId = FsCompanyModel::getOrganizationIdByDepartmentId($this->cruiseCheckDetailModel->companyId);
        } else {

            // 常规/自检

            if ($this->cruiseCheckDetailModel->templateType == CruiseTemplateModel::TYPE_3) {

                // 门店
                $role = self::ROLE_KF;
                $orgId = 0;
            } else {

                // 工厂
                $role = self::ROLE_FACTORY;
                $orgId  = CruiseCheckCompanyModel::getOrgIdById($this->cruiseOrderModel->cruiseCheckCompanyId);
            }
        }

        return [$role, $orgId];
    }

    private function sendV2(string $path, array $elementFields, array $params, string $feishuId): void
    {
        $templateArr = json_decode(file_get_contents(resource_path($path)), true);
        $templateArr['elements'][0]['fields'] = $elementFields;

        $templateJson = vsprintf(json_encode($templateArr), $params);

        dispatch((new FsMessageJob($feishuId, json_decode($templateJson, true), $this->module)));
    }

    private function buildElementField(string $content): array
    {
        return [
            'is_short' => (bool)$content,
            'text' => [
                'content' => $content,
                'tag'     => 'lark_md',
            ],
        ];
    }
}
